package project.bluetooth.com.loadsirproject.network.bean;

import android.os.Parcel;
import android.os.Parcelable;

import com.google.gson.Gson;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by lgs on 2018/1/14.
 * 返回的是对象的json通用类
 */

public class BResponse<T> implements Parcelable {

    /**
     * code : 0
     * msg : success
     * data : {"login_key":"5ab8a5f66974c1522050550","validate_type":"google"}
     */

    private String code;
    private String msg;
    private T data;

    public BResponse() {
    }

    protected BResponse(Parcel in) {
        code = in.readString();
        msg = in.readString();
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(code);
        dest.writeString(msg);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public static final Creator<BResponse> CREATOR = new Creator<BResponse>() {
        @Override
        public BResponse createFromParcel(Parcel in) {
            return new BResponse(in);
        }

        @Override
        public BResponse[] newArray(int size) {
            return new BResponse[size];
        }
    };

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public static BResponse fromJson(String json, Class clazz) {
        Gson gson = new Gson();
        Type objectType = type(BResponse.class, clazz);
        return gson.fromJson(json, objectType);
    }

    public String toJson(Class<T> clazz) {
        Gson gson = new Gson();
        Type objectType = type(BResponse.class, clazz);
        return gson.toJson(this, objectType);
    }

    private static ParameterizedType type(final Class raw, final Type... args) {
        return new ParameterizedType() {
            @Override
            public Type[] getActualTypeArguments() {
                return args;
            }

            @Override
            public Type getRawType() {
                return raw;
            }

            @Override
            public Type getOwnerType() {
                return null;
            }
        };
    }

}
